import {useEffect, useState} from "react";
import {Badge, Divider, Empty, Flex, Pagination, Spin, Tooltip, Typography, Input, Space} from "antd";
import {BookOutlined, LoadingOutlined, ReadOutlined, SearchOutlined} from "@ant-design/icons";
import * as articleController from "../../api/articleController";
import {useTheme} from "../../context/ThemeContext";

export const FeishuDocs = () => {
    const [docs, setDocs] = useState<API.ArticlePageReqVO[]>([]);
    const [total, setTotal] = useState<number>(0);
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(5);
    const [loading, setLoading] = useState<boolean>(false);
    const [searchText, setSearchText] = useState<string>("");
    const {theme: currentTheme} = useTheme();
    const isInk = currentTheme === 'ink';

    const fetchDocs = (page: number, size: number, title?: string) => {
        setLoading(true);
        articleController.getPage({
            pageNo: page,
            pageSize: size,
            title: title
        }).then((response) => {
            if (response.data && response.data.code === 0 && response.data.data) {
                const docList = response.data.data.list || [];
                setDocs(docList);
                setTotal(response.data.data.total || 0);
            }
        }).catch(error => {
            console.error("获取文档列表失败:", error);
        }).finally(() => {
            setLoading(false);
        });
    };

    useEffect(() => {
        fetchDocs(currentPage, pageSize, searchText);
    }, [currentPage, pageSize, searchText]);

    const handlePageChange = (page: number, size?: number) => {
        setCurrentPage(page);
        if (size && size !== pageSize) {
            setPageSize(size);
        }
    };

    // 处理搜索
    const handleSearch = (value: string) => {
        setSearchText(value);
        setCurrentPage(1); // 搜索时重置到第一页
    };

    const openArticleDetail = (doc: API.ArticlePageReqVO) => {
        if (!doc || !doc.id) {
            console.error('无效的文章');
            return;
        }
        console.log(doc.id)
        // 转换为字符串处理，避免大整数精度丢失
        const idStr = String(doc.id);

        // 使用字符串形式的ID打开文章详情页面
        window.open(`/doc/get?id=${idStr}`, '_blank');
    };

    const antIcon = <LoadingOutlined style={{fontSize: 24}} spin/>;

    return (
        <div style={{height: '100%', display: 'flex', flexDirection: 'column'}}>
            <Flex align="center" gap={8} style={{marginBottom: '12px'}}>
                <BookOutlined
                    style={{
                        color: isInk ? 'var(--primary-color)' : '#ff6b6b',
                        fontSize: '20px'
                    }}
                />
                <Typography.Title
                    level={4}
                    style={{
                        margin: 0,
                        fontFamily: 'var(--font-family)',
                        color: isInk ? 'var(--primary-color)' : '#ff6b6b',
                    }}
                >
                    知识库文档
                </Typography.Title>
            </Flex>

            {/* 搜索框 */}
            <Space direction="vertical" style={{ width: '100%', marginBottom: '12px' }}>
                <Input
                    placeholder="搜索文档标题..."
                    prefix={<SearchOutlined style={{ color: isInk ? '#1677ff' : '#ff6b6b' }} />}
                    allowClear
                    onChange={(e) => handleSearch(e.target.value)}
                    style={{ 
                        borderRadius: isInk ? '4px' : '8px',
                        borderColor: isInk ? '#d9d9d9' : '#ffccc7',
                        fontFamily: 'var(--font-family)'
                    }}
                    className={`search-input-${isInk ? 'ink' : 'cartoon'}`}
                />
            </Space>

            <Divider style={{margin: '4px 0 16px'}}/>

            <div style={{
                flex: 1,
                overflowY: 'auto',
                padding: '0 4px',
                marginBottom: '16px'
            }}>
                {loading ? (
                    <div style={{textAlign: 'center', padding: '40px 0'}}>
                        <Spin indicator={antIcon}/>
                        <div style={{marginTop: '8px', fontFamily: 'var(--font-family)'}}>
                            加载中...
                        </div>
                    </div>
                ) : docs.length > 0 ? (
                    <Flex vertical gap={10}>
                        {docs.map((doc, index) => (
                            <Flex
                                key={`${doc.id}-${index}`} // 使用ID和索引组合作为key，避免重复ID问题
                                gap={12}
                                style={{
                                    cursor: "pointer",
                                    padding: '10px 12px',
                                    borderRadius: isInk ? '6px' : '10px',
                                    border: `1px solid var(--border-color)`,
                                    transition: 'all 0.3s ease',
                                    backgroundColor: isInk
                                        ? 'rgba(240, 240, 240, 0.2)'
                                        : 'rgba(255, 241, 240, 0.2)',
                                    boxShadow: '0 2px 6px rgba(0, 0, 0, 0.03)'
                                }}
                                onClick={() => {
                                    openArticleDetail(doc);
                                }}
                                align="start"
                                className={`${isInk ? "doc-item-ink" : "doc-item-cartoon"} page-transition`}
                            >
                                <Badge
                                    count={<ReadOutlined style={{color: isInk ? '#1677ff' : '#ff6b6b'}}/>}
                                    style={{
                                        backgroundColor: isInk ? '#e6f4ff' : '#fff1f0',
                                        borderRadius: '50%',
                                        border: isInk ? '1px solid #bae0ff' : '1px solid #ffccc7',
                                        width: '32px',
                                        height: '32px',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                    }}
                                />
                                <Flex vertical style={{flex: 1, overflow: 'hidden'}}>
                                    <Tooltip title={doc.title}>
                                        <Typography.Text
                                            strong
                                            ellipsis={{tooltip: false}}
                                            style={{
                                                fontFamily: 'var(--font-family)',
                                                fontSize: '15px',
                                                color: isInk ? '#1677ff' : '#ff6b6b',
                                            }}
                                        >
                                            {doc.title}
                                        </Typography.Text>
                                    </Tooltip>

                                    {doc.content && (
                                        <Typography.Paragraph
                                            ellipsis={{rows: 2}}
                                            style={{
                                                margin: '4px 0 0',
                                                fontSize: '13px',
                                                color: 'rgba(0, 0, 0, 0.65)',
                                                fontFamily: 'var(--font-family)'
                                            }}
                                        >
                                            {doc.content}
                                        </Typography.Paragraph>
                                    )}

                                    {doc.tagNames && (
                                        <Flex gap={6} style={{marginTop: '6px'}}>
                                            {doc.tagNames.split(',').map((tag, i) => (
                                                <Typography.Text
                                                    key={i}
                                                    style={{
                                                        background: isInk ? '#f0f0f0' : '#fff2f0',
                                                        border: isInk ? '1px solid #d9d9d9' : '1px solid #ffccc7',
                                                        borderRadius: isInk ? '4px' : '12px',
                                                        padding: '1px 8px',
                                                        fontSize: '12px',
                                                        fontFamily: 'var(--font-family)',
                                                        color: 'rgba(0, 0, 0, 0.65)',
                                                    }}
                                                >
                                                    {tag}
                                                </Typography.Text>
                                            ))}
                                        </Flex>
                                    )}
                                </Flex>
                            </Flex>
                        ))}
                    </Flex>
                ) : (
                    <Empty
                        description={
                            <span style={{fontFamily: 'var(--font-family)'}}>
                                {searchText ? `没有找到与"${searchText}"相关的文档` : '暂无文档'}
                            </span>
                        }
                        style={{padding: '40px 0'}}
                    />
                )}
            </div>

            {total > 0 && (
                <Pagination
                    current={currentPage}
                    pageSize={pageSize}
                    total={total}
                    onChange={handlePageChange}
                    showSizeChanger
                    pageSizeOptions={['5', '10', '20']}
                    showQuickJumper={false}
                    size="small"
                    style={{
                        textAlign: 'center',
                        marginBottom: '8px',
                        fontFamily: 'var(--font-family)'
                    }}
                />
            )}

            <style>
                {`
          .doc-item-ink:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            border-color: #1677ff;
            transform: translateY(-2px);
          }
          
          .doc-item-cartoon:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            border-color: #ff6b6b;
            transform: translateY(-3px) scale(1.01);
          }
          
          .search-input-ink:hover, .search-input-ink:focus {
            border-color: #1677ff;
            box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
          }
          
          .search-input-cartoon:hover, .search-input-cartoon:focus {
            border-color: #ff6b6b;
            box-shadow: 0 0 0 2px rgba(255, 107, 107, 0.2);
          }
        `}
            </style>
        </div>
    );
}; 